package com.definesys.smecrailtransit.module.RealStatus;

import android.databinding.DataBindingUtil;
import android.support.annotation.Nullable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.definesys.smecrailtransit.R;
import com.definesys.smecrailtransit.adapter.LineStationAdapter.LineStationAdapter;
import com.definesys.smecrailtransit.adapter.SelctLineAdapter.SelectLineAdapter;
import com.definesys.smecrailtransit.adapter.SelectUserAdapter.SelectUserAdapter;
import com.definesys.smecrailtransit.api.SmecRailApi;
import com.definesys.smecrailtransit.api.SmecRailConstant;
import com.definesys.smecrailtransit.base.SmecBaseFragment;
import com.definesys.smecrailtransit.databinding.FragmentRealStatusBinding;
import com.definesys.smecrailtransit.module.RealStatus.ViewController.ViewController;
import com.definesys.smecrailtransit.module.RealStatus.bean.ELeRealNumBean;
import com.definesys.smecrailtransit.utils.ToastyUtils;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import java.util.HashMap;

import jp.wasabeef.recyclerview.animators.SlideInLeftAnimator;

import static com.definesys.smecrailtransit.MainActivity.WAY_TO_FRAGMNET;

/**
 * Created by cjy on 2017/8/23.
 */

public class RealStatusFragment extends SmecBaseFragment<RealStatusPresenter> {
    @Override
    protected RealStatusPresenter getPersenter() {
        return new RealStatusPresenter(getContext());
    }

    //RxJava,组件间通讯的静态常量
    public static final String CLOSE_DIALOG_BACKGROUND = "closeDialogBackground(Object o)";
    public static final String CHANGE_USER = "changeUserRS(Object o)";
    public static final String CHANGE_LINE = "changeLineRS(Object o)";
    public static final String LOAD = "load(Object o)";


    public static final String GET_REAL_ELE_NUM_SUCCESS="GET_REAL_ELE_NUM_SUCCESS";
    public static final String GET_REAL_ELE_NUM_FAIL="GET_REAL_ELE_NUM_FAIL";

    private FragmentRealStatusBinding fragmentRealStatusBinding;

    private LineStationAdapter lineStationAdapter;
    private SelectUserAdapter selectUserAdapter;
    private SelectLineAdapter selectLineAdapter;

    private DisplayMetrics dm;
    private ViewController viewController;
    private HashMap<String,String> map=new HashMap<>();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        fragmentRealStatusBinding= DataBindingUtil.inflate(inflater, R.layout.fragment_real_status,container,false);
        viewController = new ViewController(fragmentRealStatusBinding,getPersenter());
        dm = getResources().getDisplayMetrics();
        _initView();
        return fragmentRealStatusBinding.getRoot();
    }

    private void _initView(){
        //设置下拉刷新的属性
        fragmentRealStatusBinding.refreshLayout.setHeaderView(SmecRailConstant.getSinaRefreshView());
        fragmentRealStatusBinding.refreshLayout.setAutoLoadMore(true);
        fragmentRealStatusBinding.refreshLayout.setEnableOverScroll(false);
        fragmentRealStatusBinding.refreshLayout.setEnableLoadmore(false);
        fragmentRealStatusBinding.refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                viewController.getNetWorkData();
            }
        });

        //设置线路数据
        viewController.getLineList().add("12号线");
        viewController.getLineList().add("1号线");
        viewController.getLineList().add("2号线");
        viewController.getLineList().add("3号线");
        viewController.getLineList().add("4号线");
        viewController.getLineList().add("5号线");
        viewController.getLineList().add("9号线");
        viewController.getLineList().add("16号线");


        //设置界面显示的数据
        fragmentRealStatusBinding.nowLine.setText(viewController.getSelectLine().substring(0,viewController.getSelectLine().length()-2));
        fragmentRealStatusBinding.nowUser.setText(viewController.getSelectUser());

        //设置界面的Adapter
        lineStationAdapter = new LineStationAdapter(dm,this.mRxBus,SmecRailApi.MonthCode.REALSTATUS,getContext());
        selectUserAdapter = new SelectUserAdapter(this.mRxBus, SmecRailApi.MonthCode.REALSTATUS);
        selectLineAdapter = new SelectLineAdapter(viewController.getLineList(),this.mRxBus, SmecRailApi.MonthCode.REALSTATUS);


        viewController.setSelectLineAdapter(selectLineAdapter);
        viewController.setSelectUserAdapter(selectUserAdapter);

        //选择运营商下拉框
        fragmentRealStatusBinding.selectUser.setItemAnimator(new SlideInLeftAnimator());
        fragmentRealStatusBinding.selectUser.setLayoutManager(new LinearLayoutManager(getActivity()));
        fragmentRealStatusBinding.selectUser.setAdapter(selectUserAdapter);

        //选择线路下拉框
        fragmentRealStatusBinding.selectLine.setItemAnimator(new SlideInLeftAnimator());
        fragmentRealStatusBinding.selectLine.setLayoutManager(new LinearLayoutManager(getActivity()));
        fragmentRealStatusBinding.selectLine.setAdapter(selectLineAdapter);


        fragmentRealStatusBinding.recyclerView.setItemAnimator(new SlideInLeftAnimator());
        fragmentRealStatusBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));


        //界面图标
        fragmentRealStatusBinding.lineImg.setBackgroundResource(R.drawable.month_form_bottom);
        fragmentRealStatusBinding.userImg.setBackgroundResource(R.drawable.month_form_bottom);
    }

    public static RealStatusFragment newInstance() {
        Bundle args = new Bundle();
        RealStatusFragment fragment = new RealStatusFragment();
        fragment.setArguments(args);
        return fragment;
    }


    /**
     * 当切换tab,离开页面时，关闭本页面中的dialog背景层
     */
    @Subscribe(

            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(LOAD)
            }
    )
    public void load(Object o){
        this.viewController.getNetWorkData();
    }


    /**
     * 当切换tab,离开页面时，关闭本页面中的dialog背景层
     */
    @Subscribe(

            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(CLOSE_DIALOG_BACKGROUND)
            }
    )
    public void closeDialogBackground(Object o){
        this.fragmentRealStatusBinding.backgroundPop.setVisibility(View.GONE);
        this.fragmentRealStatusBinding.pull.setVisibility(View.GONE);
        this.fragmentRealStatusBinding.line.setVisibility(View.GONE);
    }

    @Subscribe(

            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(WAY_TO_FRAGMNET)
            }
    )
    public void refresh(String position){
        if(position.equals("2")){
            if(fragmentRealStatusBinding == null){
                return;
            }
            fragmentRealStatusBinding.getRoot().postDelayed(new Runnable() {
                @Override
                public void run() {
                    fragmentRealStatusBinding.refreshLayout.startRefresh();
                }
            },300);
        }
    }


    /**
     * 当切换运营商时
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(CHANGE_USER)
            }
    )
    public void changeUser(Object o){
        this.fragmentRealStatusBinding.pull.setVisibility(View.GONE);
        this.fragmentRealStatusBinding.userImg.setBackgroundResource(R.drawable.month_form_bottom);
        viewController.setSelectUser(String.valueOf(o));
        fragmentRealStatusBinding.nowUser.setText(viewController.getSelectUser());
        viewController.getNetWorkData();
    }

    /**
     * 当切换线路时
     */
    @Subscribe(

            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(CHANGE_LINE)
            }
    )
    public void changeLine(Object o){
        if((boolean)o){
            ToastyUtils.showWaringToast(this.fragmentRealStatusBinding.getRoot().getContext(),
                    "当前版本只有12号线的数据");
        }
        this.fragmentRealStatusBinding.line.setVisibility(View.GONE);
        this.fragmentRealStatusBinding.lineImg.setBackgroundResource(R.drawable.month_form_bottom);
    }



    /**
     * 获取页面数据成功
     */
    @Subscribe(

            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(GET_REAL_ELE_NUM_SUCCESS)
            }
    )
    public void getRealEleNumSuccess(ELeRealNumBean eLeRealNumBean){
        fragmentRealStatusBinding.recyclerView.setAdapter(lineStationAdapter);
        viewController.getLocalData();
        changeView();
        fragmentRealStatusBinding.refreshLayout.finishRefreshing();
    }

    /**
     * 获取页面数据失败
     */
    @Subscribe(

            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(GET_REAL_ELE_NUM_FAIL)
            }
    )
    public void getRealEleNumFail(Object o){
        fragmentRealStatusBinding.recyclerView.setAdapter(lineStationAdapter);
        ToastyUtils.showErrorToast(fragmentRealStatusBinding.getRoot().getContext(),"当前数据为旧数据，网络良好后请刷新");
        viewController.getLocalData();
        changeView();
        fragmentRealStatusBinding.refreshLayout.finishRefreshing();
    }

    //处理根据获取的数据，跟新页面
    private void changeView(){
        //设置运营商下拉列表
        if(viewController.getUserList() != null & viewController.getUserList().size() != 0){
            selectUserAdapter.setList(viewController.getUserList());
        }
        selectUserAdapter.notifyDataSetChanged();

        //设置线路站点显示数据
        if(viewController.getList() != null & viewController.getList().size() != 0){
            lineStationAdapter.setList(viewController.getList());
            lineStationAdapter.showAnimation = true;
        }

        fragmentRealStatusBinding.invalidateAll();

        fragmentRealStatusBinding.getRoot().postDelayed(new Runnable() {
            @Override
            public void run() {
                lineStationAdapter.showAnimation = false;
            }
        },500);
    }
}
